using System.Linq;
using Microsoft.EntityFrameworkCore;
using MVC.Db;
using MVC.Models;

namespace MVC.Repository
{
    public class EfRepository<T> : IRepository<T> where T : Father
    {

        private readonly  DbDemoSoft1 _Db;
        private readonly  DbSet<T> _yy;

        public EfRepository()
        {
            _Db = new DbDemoSoft1();
            _yy = _Db.Set<T>();
        }

        public IQueryable<T> Table
        {
            get
            {
                return _yy as IQueryable<T>;
            }
        }
        public void Delete(int id)
        {
            var father = _yy.Where(x=>x.Id==id).FirstOrDefault();
            if(father==null)
            {
                throw new System.Exception();
            }

            father.IsDeleted = true;

            _yy.Remove(father);
            _Db.SaveChanges();
        }

        public T GetById(int id)
        {
           var t = _yy.Where(x=>x.Id==id).FirstOrDefault();
           return t;
        }

        public void Insert(T father)
        {
            _yy.Add(father);
            _Db.SaveChanges();
        }


        public void Update(T father)
        {
            if(father==null)
            {
                throw new System.Exception();
            }
            if(father.Id==0)
            {
                throw new System.Exception();
            }

            _yy.Update(father);
            _Db.SaveChanges();
        }
    }
}